"use strict";

const Service = require("egg").Service;

class DictService extends Service {
  async index(
    dict_name,
    dict_code,
    { page, pageSize } = { page: 1, pageSize: 10 }
  ) {
    const { ctx, app } = this;

    // 构建查询条件
    const where = {};

    // 构建or条件数组
    const orConditions = [];

    // 添加各种可能的查询条件到orConditions数组
    if (dict_name && dict_name.trim() !== "") {
      const cleanDictName = dict_name.trim();
      orConditions.push({
        dict_name: {
          [app.Sequelize.Op.like]: `%${cleanDictName}%`,
        },
      });
    }

    if (dict_code && dict_code.trim() !== "") {
      const cleanDictCode = dict_code.trim();
      orConditions.push({
        dict_code: {
          [app.Sequelize.Op.like]: `%${cleanDictCode}%`,
        },
      });
    }

    // 只有当orConditions数组不为空时，才添加到where条件中
    if (orConditions.length > 0) {
      where[app.Sequelize.Op.or] = orConditions;
    }

    const result = await ctx.model.Dict.findAndCountAll({
      where,
      order: [["created_at", "DESC"]], // Sort by sort field and createdAt
      offset: (page - 1) * pageSize,
      limit: pageSize,
    });
    return {
      rows: result.rows,
      count: result.count,
    };
  }

  async create(dictData) {
    const { ctx } = this;

    const newDict = await ctx.model.Dict.create(dictData);
    return newDict;
  }

  async destroy(id) {
    const { ctx } = this;
    const result = await ctx.model.Dict.destroy({
      where: { id },
    });
    return result > 0; // 返回是否删除成功
  }

  async batchDelete(ids) {
    const { ctx } = this;
    const result = await ctx.model.Dict.destroy({
      where: { id: ids },
    });
    return result > 0; // 返回是否删除成功
  }

  async update(id, dictData) {
    const { ctx } = this;
    const [updatedRows] = await ctx.model.Dict.update(dictData, {
      where: { id },
    });
    return updatedRows > 0; // 返回是否更新成功
  }

  async dictItemsByDictCode(dict_code) {
    const { ctx } = this;

    // 使用 include 进行关联查询
    const dict = await ctx.model.Dict.findOne({
      where: { dict_code },
      include: [
        {
          model: ctx.model.DictItem,
          as: "dict_item",
          where: { status: 1 }, // 只查询启用的字典项
        },
      ],
    });

    if (!dict) {
      return null;
    }

    // 返回字典类型和字典项
    return dict.dict_item;

    // const dict = await ctx.model.Dict.findOne({
    //   where: { dict_code: dict_code },
    // });

    // if (!dict) {
    //   return null;
    // }

    // // 查询字典项列表，按排序字段升序排列
    // const items = await ctx.model.DictItem.findAll({
    //   where: { dict_id: dict.id, status: 1 },
    //   order: [["created_at", "DESC"]],
    // });

    // return items;
  }
}

module.exports = DictService;
